<template>
  <div class="component-library">
    <div class="section-header">
      <h2>组件库</h2>
      <el-input
        v-model="searchQuery"
        placeholder="搜索组件..."
        prefix-icon="Search"
        clearable
        class="search-input"
      />
    </div>

    <div class="library-tabs">
      <el-tabs v-model="activeTab">
        <el-tab-pane label="基础组件" name="basic">
          <div class="component-grid">
            <div 
              v-for="component in filteredComponents.basic" 
              :key="component.id"
              class="component-item"
              draggable="true"
              @dragstart="handleDragStart($event, component)"
            >
              <div class="component-icon">
                <el-icon><component :is="component.icon" /></el-icon>
              </div>
              <div class="component-name">{{ component.name }}</div>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="布局组件" name="layout">
          <div class="component-grid">
            <div 
              v-for="component in filteredComponents.layout" 
              :key="component.id"
              class="component-item"
              draggable="true"
              @dragstart="handleDragStart($event, component)"
            >
              <div class="component-icon">
                <el-icon><component :is="component.icon" /></el-icon>
              </div>
              <div class="component-name">{{ component.name }}</div>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="表单组件" name="form">
          <div class="component-grid">
            <div 
              v-for="component in filteredComponents.form" 
              :key="component.id"
              class="component-item"
              draggable="true"
              @dragstart="handleDragStart($event, component)"
            >
              <div class="component-icon">
                <el-icon><component :is="component.icon" /></el-icon>
              </div>
              <div class="component-name">{{ component.name }}</div>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="数据展示" name="data">
          <div class="component-grid">
            <div 
              v-for="component in filteredComponents.data" 
              :key="component.id"
              class="component-item"
              draggable="true"
              @dragstart="handleDragStart($event, component)"
            >
              <div class="component-icon">
                <el-icon><component :is="component.icon" /></el-icon>
              </div>
              <div class="component-name">{{ component.name }}</div>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="导航组件" name="navigation">
          <div class="component-grid">
            <div 
              v-for="component in filteredComponents.navigation" 
              :key="component.id"
              class="component-item"
              draggable="true"
              @dragstart="handleDragStart($event, component)"
            >
              <div class="component-icon">
                <el-icon><component :is="component.icon" /></el-icon>
              </div>
              <div class="component-name">{{ component.name }}</div>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="反馈组件" name="feedback">
          <div class="component-grid">
            <div 
              v-for="component in filteredComponents.feedback" 
              :key="component.id"
              class="component-item"
              draggable="true"
              @dragstart="handleDragStart($event, component)"
            >
              <div class="component-icon">
                <el-icon><component :is="component.icon" /></el-icon>
              </div>
              <div class="component-name">{{ component.name }}</div>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="我的组件" name="custom">
          <div class="custom-components">
            <el-empty v-if="!components.custom || components.custom.length === 0" description="暂无自定义组件">
              <el-button type="primary" @click="handleAddCustom">创建自定义组件</el-button>
            </el-empty>
            <div v-else class="component-grid">
              <div 
                v-for="component in filteredComponents.custom" 
                :key="component.id"
                class="component-item"
                draggable="true"
                @dragstart="handleDragStart($event, component)"
                @contextmenu.prevent="showCustomMenu(component)"
              >
                <div class="component-icon">
                  <el-icon><component :is="component.icon" /></el-icon>
                </div>
                <div class="component-name">{{ component.name }}</div>
              </div>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>

    <el-dialog v-model="customDialogVisible" title="创建自定义组件" width="500px">
      <el-form :model="newCustomComponent" label-width="100px">
        <el-form-item label="组件名称">
          <el-input v-model="newCustomComponent.name" />
        </el-form-item>
        <el-form-item label="组件类型">
          <el-select v-model="newCustomComponent.type" placeholder="请选择组件类型">
            <el-option label="容器" value="container" />
            <el-option label="表单项" value="form-item" />
            <el-option label="数据展示" value="data-display" />
            <el-option label="交互元素" value="interactive" />
          </el-select>
        </el-form-item>
        <el-form-item label="图标">
          <el-select v-model="newCustomComponent.icon" placeholder="请选择图标">
            <el-option label="矩形" value="CreditCard" />
            <el-option label="文本" value="Document" />
            <el-option label="图像" value="Picture" />
            <el-option label="按钮" value="SetUp" />
            <el-option label="表格" value="Grid" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="customDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addCustomComponent">创建</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dropdown-menu
      v-model:visible="dropdownVisible"
      ref="customDropdownRef"
      :style="dropdownPosition"
      class="custom-dropdown"
    >
      <el-dropdown-item @click="editCustomComponent">编辑</el-dropdown-item>
      <el-dropdown-item @click="duplicateCustomComponent">复制</el-dropdown-item>
      <el-dropdown-item divided @click="deleteCustomComponent">删除</el-dropdown-item>
    </el-dropdown-menu>
  </div>
</template>

<script setup>
import { ref, computed, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Search,
  CreditCard,
  Document,
  SetUp,
  Menu,
  Grid,
  Picture,
  ChatDotRound,
  User,
  List,
  Connection,
  Operation,
  Notification,
  Switch,
  Pointer,
  Edit
} from '@element-plus/icons-vue'

// 组件库数据
const components = reactive({
  basic: [
    { id: 'b1', name: '矩形', icon: 'CreditCard', type: 'rectangle' },
    { id: 'b2', name: '文本', icon: 'Document', type: 'text' },
    { id: 'b3', name: '图片', icon: 'Picture', type: 'image' },
    { id: 'b4', name: '按钮', icon: 'SetUp', type: 'button' },
    { id: 'b5', name: '图标', icon: 'Edit', type: 'icon' }
  ],
  layout: [
    { id: 'l1', name: '容器', icon: 'CreditCard', type: 'container' },
    { id: 'l2', name: '行', icon: 'Menu', type: 'row' },
    { id: 'l3', name: '列', icon: 'Operation', type: 'column' },
    { id: 'l4', name: '卡片', icon: 'CreditCard', type: 'card' },
    { id: 'l5', name: '标签页', icon: 'Document', type: 'tabs' }
  ],
  form: [
    { id: 'f1', name: '输入框', icon: 'Edit', type: 'input' },
    { id: 'f2', name: '选择器', icon: 'List', type: 'select' },
    { id: 'f3', name: '单选框', icon: 'Connection', type: 'radio' },
    { id: 'f4', name: '复选框', icon: 'SetUp', type: 'checkbox' },
    { id: 'f5', name: '开关', icon: 'Switch', type: 'switch' }
  ],
  data: [
    { id: 'd1', name: '表格', icon: 'Grid', type: 'table' },
    { id: 'd2', name: '列表', icon: 'List', type: 'list' },
    { id: 'd3', name: '描述列表', icon: 'Document', type: 'description' },
    { id: 'd4', name: '树形控件', icon: 'Operation', type: 'tree' },
    { id: 'd5', name: '标签', icon: 'Document', type: 'tag' }
  ],
  navigation: [
    { id: 'n1', name: '菜单', icon: 'Menu', type: 'menu' },
    { id: 'n2', name: '导航栏', icon: 'Menu', type: 'navbar' },
    { id: 'n3', name: '步骤条', icon: 'Connection', type: 'steps' },
    { id: 'n4', name: '分页', icon: 'Document', type: 'pagination' },
    { id: 'n5', name: '面包屑', icon: 'Connection', type: 'breadcrumb' }
  ],
  feedback: [
    { id: 'fb1', name: '对话框', icon: 'ChatDotRound', type: 'dialog' },
    { id: 'fb2', name: '抽屉', icon: 'Document', type: 'drawer' },
    { id: 'fb3', name: '通知', icon: 'Notification', type: 'notification' },
    { id: 'fb4', name: '加载中', icon: 'Operation', type: 'loading' },
    { id: 'fb5', name: '进度条', icon: 'Connection', type: 'progress' }
  ],
  custom: []
})

const activeTab = ref('basic')
const searchQuery = ref('')
const customDialogVisible = ref(false)
const newCustomComponent = ref({
  name: '',
  type: 'container',
  icon: 'CreditCard'
})

// 下拉菜单相关
const dropdownVisible = ref(false)
const dropdownPosition = ref({ left: '0px', top: '0px' })
const selectedCustomComponent = ref(null)
const customDropdownRef = ref(null)

// 过滤组件
const filteredComponents = computed(() => {
  const query = searchQuery.value.toLowerCase()
  if (!query) return components
  
  const filtered = {}
  for (const category in components) {
    filtered[category] = components[category].filter(comp => 
      comp.name.toLowerCase().includes(query) || 
      comp.type.toLowerCase().includes(query)
    )
  }
  return filtered
})

// 处理拖拽开始
const handleDragStart = (event, component) => {
  event.dataTransfer.setData('application/json', JSON.stringify(component))
  event.dataTransfer.effectAllowed = 'copy'
}

// 添加自定义组件
const handleAddCustom = () => {
  customDialogVisible.value = true
  newCustomComponent.value = {
    name: '',
    type: 'container',
    icon: 'CreditCard'
  }
}

const addCustomComponent = () => {
  if (!newCustomComponent.value.name) {
    ElMessage.warning('请输入组件名称')
    return
  }
  
  const id = `custom-${Date.now()}`
  const customComponent = {
    id,
    name: newCustomComponent.value.name,
    type: newCustomComponent.value.type,
    icon: newCustomComponent.value.icon,
    isCustom: true
  }
  
  components.custom.push(customComponent)
  customDialogVisible.value = false
  activeTab.value = 'custom'
  ElMessage.success('自定义组件创建成功')
}

// 显示自定义组件的右键菜单
const showCustomMenu = (component) => {
  selectedCustomComponent.value = component
  // 设置菜单位置
  const event = window.event
  dropdownPosition.value = {
    left: `${event.clientX}px`,
    top: `${event.clientY}px`
  }
  
  // 显示菜单
  dropdownVisible.value = true
  
  // 监听点击事件以关闭菜单
  setTimeout(() => {
    document.addEventListener('click', handleClickOutside)
  }, 0)
}

// 处理菜单外的点击
const handleClickOutside = () => {
  dropdownVisible.value = false
  document.removeEventListener('click', handleClickOutside)
}

// 编辑自定义组件
const editCustomComponent = () => {
  if (!selectedCustomComponent.value) return
  
  customDialogVisible.value = true
  newCustomComponent.value = {
    name: selectedCustomComponent.value.name,
    type: selectedCustomComponent.value.type,
    icon: selectedCustomComponent.value.icon
  }
  
  // 关闭菜单
  dropdownVisible.value = false
  
  // 监听对话框关闭事件
  const updateCustomComponent = () => {
    const index = components.custom.findIndex(c => c.id === selectedCustomComponent.value.id)
    if (index !== -1) {
      components.custom[index] = {
        ...components.custom[index],
        name: newCustomComponent.value.name,
        type: newCustomComponent.value.type,
        icon: newCustomComponent.value.icon
      }
      ElMessage.success('组件已更新')
    }
  }
  
  // 更新组件
  customDialogVisible.value = false
  updateCustomComponent()
}

// 复制自定义组件
const duplicateCustomComponent = () => {
  if (!selectedCustomComponent.value) return
  
  const duplicated = {
    ...selectedCustomComponent.value,
    id: `custom-${Date.now()}`,
    name: `${selectedCustomComponent.value.name} (副本)`
  }
  
  components.custom.push(duplicated)
  ElMessage.success('组件已复制')
  dropdownVisible.value = false
}

// 删除自定义组件
const deleteCustomComponent = () => {
  if (!selectedCustomComponent.value) return
  
  ElMessageBox.confirm(
    `确定要删除组件 "${selectedCustomComponent.value.name}" 吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    const index = components.custom.findIndex(c => c.id === selectedCustomComponent.value.id)
    if (index !== -1) {
      components.custom.splice(index, 1)
      ElMessage.success('组件已删除')
    }
  }).catch(() => {})
  
  dropdownVisible.value = false
}
</script>

<style scoped>
.component-library {
  padding: 16px;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.section-header h2 {
  margin: 0;
  font-size: 20px;
  color: #303133;
}

.search-input {
  width: 200px;
}

.library-tabs {
  flex: 1;
  overflow-y: auto;
}

.component-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
  gap: 16px;
  padding: 16px 0;
}

.component-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  background-color: #f5f7fa;
  padding: 16px;
  border-radius: 4px;
  cursor: grab;
  transition: transform 0.2s, box-shadow 0.2s;
}

.component-item:hover {
  background-color: #f0f2f5;
  transform: translateY(-2px);
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.component-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 40px;
  height: 40px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.component-icon i {
  font-size: 20px;
  color: #606266;
}

.component-name {
  font-size: 14px;
  color: #606266;
  text-align: center;
}

.custom-dropdown {
  position: fixed;
  z-index: 3000;
  margin: 0;
  padding: 0;
  border-radius: 4px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}
</style> 